import ResizeObserver from 'resize-observer-polyfill'

const elementListeners = new Map()
function onResize(entries) {
  for (const entry of entries) {
    const { target } = entry
    const listenerSet = elementListeners.get(target)
    if (listenerSet !== null && listenerSet !== undefined) {
      listenerSet.forEach((listener) => {
        return listener(entry)
      })
    }
  }
}
// Note:
const resizeObserver = new ResizeObserver(onResize)

export function observe(element, callback) {
  if (!elementListeners.has(element)) {
    elementListeners.set(element, new Set())
    resizeObserver.observe(element)
  }
  elementListeners.get(element).add(callback)
}
export function unobserve(element, callback) {
  if (elementListeners.has(element)) {
    elementListeners.get(element).delete(callback)
    if (!elementListeners.get(element).size) {
      resizeObserver.unobserve(element)
      elementListeners.delete(element)
    }
  }
}
